import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  message, 
  Modal, 
  Form, 
  Input, 
  InputNumber, 
  Space, 
  Tag,
  Upload
} from 'antd';
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  ExclamationCircleOutlined,
  UploadOutlined
} from '@ant-design/icons';
import { bookApi, uploadApi } from '../../api';

const { TextArea } = Input;
const { confirm } = Modal;

const Books = () => {
  const [loading, setLoading] = useState(false);
  const [books, setBooks] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchText, setSearchText] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingBook, setEditingBook] = useState(null);
  const [form] = Form.useForm();
  const [uploading, setUploading] = useState(false);
  const [coverUrl, setCoverUrl] = useState('');
  const [imageKey, setImageKey] = useState(0);

  // 获取书籍列表
  const fetchBooks = async (page = 0, size = 10, name = '') => {
    setLoading(true);
    try {
      const response = await bookApi.getAllBooks(page, size, name);
      if (response.success) {
        setBooks(response.data.content || []);
        setPagination({
          current: page + 1,
          pageSize: size,
          total: response.data.totalElements || 0
        });
      } else {
        message.error(response.message || '获取书籍列表失败');
      }
    } catch (error) {
      console.error('获取书籍列表错误:', error);
      message.error('获取书籍列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchBooks();
  }, []);

  // 监听模态框关闭，确保状态正确清理
  useEffect(() => {
    if (!modalVisible) {
      setCoverUrl('');
      setUploading(false);
      setImageKey(0);
    }
  }, [modalVisible]);

  // 处理表格变化
  const handleTableChange = (pagination) => {
    fetchBooks(pagination.current - 1, pagination.pageSize, searchText);
  };

  // 处理搜索
  const handleSearch = () => {
    fetchBooks(0, pagination.pageSize, searchText);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchText('');
    fetchBooks(0, pagination.pageSize, '');
  };

  // 打开添加/编辑模态框
  const showModal = (book = null) => {
    setEditingBook(book);
    setModalVisible(true);
    if (book) {
      form.setFieldsValue(book);
      setCoverUrl(book.cover || '');
    } else {
      form.resetFields();
      setCoverUrl('');
    }
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
    setEditingBook(null);
    form.resetFields();
    setCoverUrl('');
    setImageKey(0);
  };

  // 处理文件上传
  const handleUpload = async (options) => {
    const { file, onSuccess, onError } = options;
    
    setUploading(true);
    try {
      const response = await uploadApi.uploadImage(file);
      if (response && response.success) {
        const fileUrl = response.data.url;
        
        // 更新状态，添加小延迟确保服务器准备就绪
        setTimeout(() => {
          setCoverUrl(fileUrl);
          setImageKey(prev => prev + 1);
          form.setFieldsValue({ cover: fileUrl });
        }, 100);
        
        // 调用onSuccess，传递正确的参数
        if (onSuccess) {
          onSuccess({
            url: fileUrl,
            name: file.name,
            status: 'done'
          });
        }
        
        message.success('封面上传成功');
      } else {
        const errorMsg = response?.message || '上传失败';
        const error = new Error(errorMsg);
        if (onError) {
          onError(error);
        }
        message.error(errorMsg);
      }
    } catch (error) {
      console.error('上传错误:', error);
      const errorMsg = error.message || '网络错误，上传失败';
      if (onError) {
        onError(error);
      }
      message.error(errorMsg);
    } finally {
      setUploading(false);
    }
  };

  // 上传前的校验
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片大小不能超过5MB');
      return false;
    }
    
    return true;
  };

  // 保存书籍
  const handleSave = async (values) => {
    try {
      let response;
      if (editingBook) {
        // 编辑
        response = await bookApi.updateBook(editingBook.id, values);
      } else {
        // 新增
        response = await bookApi.createBook(values);
      }

      if (response.success) {
        message.success(`${editingBook ? '更新' : '添加'}书籍成功`);
        setModalVisible(false);
        setEditingBook(null);
        setCoverUrl('');
        setImageKey(0);
        form.resetFields();
        // 刷新列表
        fetchBooks(pagination.current - 1, pagination.pageSize, searchText);
      } else {
        message.error(response.message || `${editingBook ? '更新' : '添加'}书籍失败`);
      }
    } catch (error) {
      console.error('保存书籍错误:', error);
      message.error(`${editingBook ? '更新' : '添加'}书籍失败`);
    }
  };

  // 删除书籍
  const handleDelete = (book) => {
    confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除书籍 "${book.name}" 吗？删除后无法恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await bookApi.deleteBook(book.id);
          if (response.success) {
            message.success('删除书籍成功');
            // 刷新列表
            fetchBooks(pagination.current - 1, pagination.pageSize, searchText);
          } else {
            message.error(response.message || '删除书籍失败');
          }
        } catch (error) {
          console.error('删除书籍错误:', error);
          message.error('删除书籍失败');
        }
      }
    });
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60
    },
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      width: 80,
      render: (cover) => (
        cover ? (
          <img
            width={50}
            height={70}
            src={cover}
            style={{ 
              borderRadius: 4,
              border: '1px solid #d9d9d9',
              display: 'block'
            }}
            onError={(e) => {
              // 如果加载失败，显示占位符
              e.target.style.display = 'none';
              const placeholder = document.createElement('div');
              placeholder.style.cssText = `
                width: 50px; 
                height: 70px; 
                background-color: #f5f5f5; 
                display: flex; 
                align-items: center; 
                justify-content: center; 
                border-radius: 4px; 
                color: #999; 
                font-size: 10px;
                border: 1px solid #d9d9d9;
              `;
              placeholder.textContent = '无图';
              e.target.parentNode.replaceChild(placeholder, e.target);
            }}
            alt="书籍封面"
          />
        ) : (
          <div style={{ width: 50, height: 70, backgroundColor: '#f5f5f5', display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 4, color: '#999', fontSize: 12 }}>
            无图
          </div>
        )
      )
    },
    {
      title: '书名',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 120
    },
    {
      title: 'ISBN',
      dataIndex: 'isbn',
      key: 'isbn',
      width: 140
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 80,
      render: (price) => `¥${price}`
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 80,
      render: (stock) => (
        <Tag color={stock > 10 ? 'green' : stock > 0 ? 'orange' : 'red'}>
          {stock}
        </Tag>
      )
    },
    {
      title: '出版社',
      dataIndex: 'publisher',
      key: 'publisher',
      width: 120,
      ellipsis: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
      render: (text) => text ? new Date(text).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Button
            type="primary"
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>书籍管理</h2>
        <Space>
          <Input
            placeholder="搜索书名"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: 200 }}
          />
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            onClick={handleSearch}
          >
            搜索
          </Button>
          <Button onClick={handleReset}>重置</Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => showModal()}
          >
            添加书籍
          </Button>
        </Space>
      </div>
      
      <Table
        columns={columns}
        dataSource={books}
        rowKey="id"
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
        scroll={{ x: 1200 }}
      />

      {/* 添加/编辑模态框 */}
      <Modal
        title={editingBook ? '编辑书籍' : '添加书籍'}
        open={modalVisible}
        onCancel={handleCancel}
        footer={null}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            name="name"
            label="书名"
            rules={[{ required: true, message: '请输入书名' }]}
          >
            <Input placeholder="请输入书名" />
          </Form.Item>

          <Form.Item
            name="author"
            label="作者"
            rules={[{ required: true, message: '请输入作者' }]}
          >
            <Input placeholder="请输入作者" />
          </Form.Item>

          <Form.Item
            name="isbn"
            label="ISBN编号"
            rules={[{ required: true, message: '请输入ISBN编号' }]}
          >
            <Input placeholder="请输入ISBN编号" />
          </Form.Item>

          <div style={{ display: 'flex', gap: 16 }}>
            <Form.Item
              name="price"
              label="价格"
              rules={[{ required: true, message: '请输入价格' }]}
              style={{ flex: 1 }}
            >
              <InputNumber
                placeholder="请输入价格"
                min={0}
                precision={2}
                style={{ width: '100%' }}
                addonBefore="¥"
              />
            </Form.Item>

            <Form.Item
              name="stock"
              label="库存"
              rules={[{ required: true, message: '请输入库存' }]}
              style={{ flex: 1 }}
            >
              <InputNumber
                placeholder="请输入库存"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </div>

          <Form.Item
            name="publisher"
            label="出版社"
          >
            <Input placeholder="请输入出版社" />
          </Form.Item>

          <Form.Item
            name="cover"
            label="封面图片"
          >
            <div>
              <Upload
                key={editingBook ? `upload-${editingBook.id}` : 'upload-new'}
                customRequest={handleUpload}
                beforeUpload={beforeUpload}
                showUploadList={false}
                accept="image/*"
                disabled={uploading}
              >
                <Button icon={<UploadOutlined />} loading={uploading}>
                  {uploading ? '上传中...' : '选择图片'}
                </Button>
              </Upload>
              {coverUrl && (
                <div style={{ marginTop: 8 }}>
                  <img
                    key={`cover-${imageKey}`}
                    width={100}
                    height={140}
                    src={`${coverUrl}?t=${Date.now()}`}
                    style={{ 
                      border: '1px solid #d9d9d9', 
                      borderRadius: 4,
                      display: 'block'
                    }}
                    onError={(e) => {
                      // 延迟重试，可能是服务器还没准备好
                      setTimeout(() => {
                        e.target.src = coverUrl;
                      }, 1000);
                    }}
                    onLoad={(e) => {
                      e.target.style.display = 'block';
                    }}
                    alt="封面预览"
                  />

                </div>
              )}
              <Input
                value={coverUrl}
                onChange={(e) => {
                  const newUrl = e.target.value;
                  setCoverUrl(newUrl);
                  setImageKey(prev => prev + 1);
                  form.setFieldsValue({ cover: newUrl });
                }}
                placeholder="或直接输入图片URL"
                style={{ marginTop: 8 }}
              />
            </div>
          </Form.Item>

          <Form.Item
            name="description"
            label="书籍描述"
          >
            <TextArea 
              rows={4} 
              placeholder="请输入书籍描述" 
            />
          </Form.Item>

          <Form.Item style={{ marginTop: 24, textAlign: 'right' }}>
            <Space>
              <Button onClick={handleCancel}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingBook ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Books; 